package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"github.com/dgrijalva/jwt-go/v4"
	"net/http"
	"time"
	"user/common"
	"user/models"
)

type LoginController struct {
	beego.Controller
}

func (c *LoginController) Login() {
	username := c.GetString("une")
	password := c.GetString("pwd")
	data, err := models.Log(username)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": http.StatusCreated,
			"msg":  err.Error(),
		}
		c.ServeJSON()
		return
	}
	if data.Password != password {
		c.Data["json"] = map[string]interface{}{
			"code": http.StatusCreated,
			"msg":  "密码错误",
		}
		c.ServeJSON()
		return
	}
	token, err := common.CreateToken(&common.MyCustomClaims{
		Id:       data.Id,
		Username: username,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: jwt.NewTime(float64(time.Now().Unix() + 86400)),
		},
	})
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": http.StatusCreated,
			"msg":  err.Error(),
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": http.StatusOK,
		"msg":  "登陆成功",
		"data": token,
	}
	c.ServeJSON()
	return
}
